package com.hj.service.impl;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.hj.config.ConfigConstants;
import com.hj.model.CompressDescFile;
import com.hj.model.FileAttribute;
import com.hj.service.FilePreview;
import com.hj.util.FileUtils;
import com.hj.util.OfficeToPdf;
import com.hj.util.ZipReader;
import com.hj.web.filter.BaseUrlFilter;

/**
 * @author dehui dou
 * @date 2020/10/3 19:02
 * @description
 */
@Service
public class CompressInnerFilePreviewImpl implements FilePreview {
    @Autowired
    private ZipReader zipReader;
    @Autowired
    private OfficeToPdf officeToPdf;

    /**
     * @author dehui dou
     * @description 文件预览处理实现
     * @param model
     * @param fileAttribute
     * @return java.lang.String
     */
    @Override
    public String filePreviewHandle(Model model, FileAttribute fileAttribute) {
        String fileAllName = fileAttribute.getFileViewName();
        String fileRealName = fileAttribute.getFileRealName();
        String[] split = fileAllName.split(Pattern.quote(System.getProperty("file.separator")));
        String fileUniqueId = split[0];
        String fileName = split[1];
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        String viewFileName;
        if (FileUtils.listPictureTypes().contains(fileType.toLowerCase())) {
            viewFileName = fileUniqueId + "/" + fileName;
            List<String> imgUrls = Lists.newArrayList(viewFileName);
            model.addAttribute("fileRealName", fileRealName);
            model.addAttribute("currentUrl", viewFileName);
            return "picture";
        }
        if (FileUtils.listArchiveTypes().contains(fileType.toLowerCase())) {
            return compressInnerFileHandle(model, fileName, fileType, fileUniqueId, fileRealName);
        }
        if (FileUtils.listOfficeTypes().contains(fileType.toLowerCase())) {
            String officeInputFilePath = ConfigConstants.getFileDir() + File.separator + fileAllName;
            String pdfOutputFilePath = ConfigConstants.getFileDir() + File.separator
                + fileAllName.substring(0, fileAllName.lastIndexOf(".")) + ".pdf";
            File pdfFile = new File(pdfOutputFilePath);
            if (!pdfFile.exists()) {
                officeToPdf.openOfficeToPDF(officeInputFilePath, pdfOutputFilePath);
            }
            viewFileName = fileUniqueId + "/" + fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
            model.addAttribute("pdfUrl", viewFileName);
            return "pdf";
        }
        if (Arrays.asList(ConfigConstants.getSimText()).contains(fileType.toLowerCase())) {
            viewFileName = fileUniqueId + "/" + fileName;
            model.addAttribute("ordinaryUrl", viewFileName);
            return "txt";
        }
        if (Arrays.asList(ConfigConstants.getMedia()).contains(fileType.toLowerCase())) {
            viewFileName = fileUniqueId + "/" + fileName;
            model.addAttribute("mediaUrl", BaseUrlFilter.getBaseUrl() + viewFileName);
            if ("flv".equalsIgnoreCase(fileType)) {
                return "flv";
            }
            return "media";
        }
        if ("pdf".equalsIgnoreCase(fileType)) {
            viewFileName = fileUniqueId + "/" + fileName;
            model.addAttribute("pdfUrl", viewFileName);
            return "pdf";
        }
        if ("dwg".equalsIgnoreCase(fileType)) {

        }
        return "other";
    }

    /**
     * @author dehui dou
     * @description
     * @param model
     * @param fileName
     * @param extension
     * @param oldFileUniqueId
     * @param fileRealName
     * @return java.lang.String
     */
    private String compressInnerFileHandle(Model model, String fileName, String extension, String oldFileUniqueId,
        String fileRealName) {
        String fileUniqueId = fileName.substring(0, fileName.lastIndexOf("."));
        String descFilePath = ConfigConstants.getFileDir() + fileUniqueId + File.separator + fileUniqueId + ".txt";
        String compressDirPath = ConfigConstants.getFileDir() + File.separator + fileUniqueId;
        File file = new File(compressDirPath);
        String fileTree = null;
        if (!file.exists()) {
            file.mkdirs();
            String filePath =
                ConfigConstants.getFileDir() + File.separator + oldFileUniqueId + File.separator + fileName;
            CompressDescFile descFile = null;
            if ("zip".equalsIgnoreCase(extension) || "jar".equalsIgnoreCase(extension)
                || "gzip".equalsIgnoreCase(extension)) {
                descFile = zipReader.readZipFile(filePath, fileUniqueId, fileRealName);
            } else if ("rar".equalsIgnoreCase(extension)) {
                descFile = zipReader.unRar(filePath, fileUniqueId, fileRealName);
            } else if ("7z".equalsIgnoreCase(extension)) {
                descFile = zipReader.read7zFile(filePath, fileUniqueId, fileRealName);
            }
            fileTree = descFile.getFileTree();
            if (StringUtils.isNotEmpty(fileTree)) {
                FileUtils.savaStringToFile(JSONObject.toJSONString(descFile), descFilePath);
            }
        } else {
            String descFileStr = FileUtils.readFile(descFilePath);
            CompressDescFile descFile = JSONObject.parseObject(descFileStr, CompressDescFile.class);
            fileTree = descFile.getFileTree();
        }
        if (fileTree != null && !"null".equals(fileTree)) {
            model.addAttribute("fileTree", fileTree);
            return "compress";
        } else {
            model.addAttribute("fileType", extension);
            model.addAttribute("msg", "压缩文件类型不受支持，尝试在压缩的时候选择RAR4格式");
            return "fileNotSupported";
        }
    }
}
